package gw.com.android.ui.positions;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.ui.MainActivity;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.ui.quote2.NewQuoteFragment;
import gw.com.android.ui.trade.TradeBusiness;
import gw.com.android.utils.ColorThemeUtil;
import gw.com.android.utils.ServerConnnectUtil;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.CommonUtils;
import www.com.library.util.NetworkMonitor;
import www.com.library.util.StringFormatter;

/**
 * Created by reeta.zou on 2016/7/7.
 */
public class PositionAdapter extends RecylerListAdapter {

    private DataItemResult mList;
    /**
     * 展开项id
     */
    private int mExpandOrderId = -1;

    /**
     * 初始化界面数据
     *
     * @param context
     */
    public PositionAdapter(Context context, RecyclerView mView) {
        super(context, mView);
        mList = new DataItemResult();
        mList.appendItems(DataManager.instance().mPositionInfoList);
        notifyDataChanged();
    }

    @Override
    public void refreshData() {
        Logger.i("Position refreshData 持仓列表回包接收到回调");
        mList.clear();
        mList.appendItems(DataManager.instance().mPositionInfoList);
        notifyDataChanged();
    }

    @Override
    public void refreshPrice(ArrayList<Integer> codeId) {
        super.refreshPrice(codeId);
//        Logger.e("持仓列表刷新11，refreshQuotePrice codeId = " + codeId);
        if(!mIsRefreshing && null != codeId && codeId.size() > 0){
//            Logger.e("持仓列表刷新，refreshQuotePrice codeId = " + codeId);
            int count = mList.getDataCount();
            for (int i = 0; i < count; i++){
                for (int j = 0; j < codeId.size(); j++){
                    if(mList.getItem(i).getInt(GTSConst.JSON_KEY_CODEID) == codeId.get(j)){
                        notifyItemChanged(i,mList.getItem(i));
                    }
                }
            }
        }
    }

    @Override
    public void refreshOrder(int orderId) {
        super.refreshOrder(orderId);
        Logger.e("持仓列表刷新，refreshQuotePrice orderId = " + orderId);
        if(!mIsRefreshing){
            int count = mList.getDataCount();
            for (int i = 0; i < count; i++){
                if(mList.getItem(i).getInt(GTSConst.JSON_KEY_ID) == orderId){
                    notifyItemChanged(i,mList.getItem(i));
                    break;
                }
            }
        }
    }

    public int getItemCount() {
        if(null != mList){
            return mList.getDataCount();
        }
        return 0;
    }

    public DataItemDetail getItem(int position) {
        if (position < 0 || position >= mList.getDataCount()) {
            return null;
        }

        if(null !=  mList && null != mList.getItem(position)){
            return mList.getItem(position);
        }

        return null;
    }

    @Override
    public void updateViews(RecyclerView.ViewHolder viewholder, int position) {
        DataItemDetail mItem = getItem(position);
//        mItem.printString();
        ListItemView mItemView = (ListItemView) viewholder;
        if (mExpandOrderId == mItem.getInt(GTSConst.JSON_KEY_ID)) {
            mItemView.btnLayout.setVisibility(View.VISIBLE);
        } else {
            mItemView.btnLayout.setVisibility(View.GONE);
        }
        // 为按钮添加相关tag值，方便后续点击事件调用参数
        mItemView.itemView.setTag(position);
        if(null != mItem){
//            mPrecision = new ProductPrecision(0,mItem.digit);
            mItemView.prdnameV.setText(DataManager.instance().getPrdName(mItem));
            mItemView.orderIdV.setText("#" + String.valueOf(mItem.getInt(GTSConst.JSON_KEY_ID)));

            updateViews(mItemView, mItem);
        }
    }

    @Override
    public void updateViews(RecyclerView.ViewHolder holder, List payloads) {
        DataItemDetail item = (DataItemDetail) payloads.get(0);
        ListItemView mItemView = (ListItemView) holder;
        if (null != item) {
            updateViews(mItemView, item);
        }
    }

    /**
     * 刷新界面元素
     * @param mItemView
     */
    private synchronized void updateViews(ListItemView mItemView, DataItemDetail mItem){
        // 买卖类型和手数
        m_spannableTitle.reset();

        if (mItem.getInt(GTSConst.JSON_KEY_DIRECTION) == AppContances.TRADE_TYPE_BUY) {
            m_spannableTitle.append(AppMain.getAppString(R.string.order_trade_buy_lot, mItem.getString(GTSConst.JSON_KEY_VOLUME)));
        } else {
            m_spannableTitle.append(AppMain.getAppString(R.string.order_trade_sell_lot, mItem.getString(GTSConst.JSON_KEY_VOLUME)));
        }
        mItemView.dirV.setText(m_spannableTitle.getBuilder());
        mItemView.swapV.setText(AppMain.getAppString(R.string.order_item_title_swap) + mItem.getString(GTSConst.JSON_KEY_INTEREST));
        mItemView.commissionV.setText(AppMain.getAppString(R.string.order_item_title_commission) + mItem.getString(GTSConst.JSON_KEY_COMMISSION));
        // 开仓价
        mItemView.donePrice.setText(mItem.getString(GTSConst.JSON_KEY_OPENPRICE));
        mItemView.profitV.setText(mItem.getString(GTSConst.JSON_KEY_PROFIT));
        mItemView.timeV.setText(StringFormatter.instance().secToDateTime(mItem.getInt(GTSConst.JSON_KEY_TIME)));
        // 净值盈亏涨跌
        ColorThemeUtil.instance().setPriceColor(mItemView.profitV,mItem.getInt(GTSConst.JSON_KEY_PROFITSTATE));

        setClosePriceColor(mItemView.closePrice,mItem);

        if (mItem.getString(GTSConst.JSON_KEY_STOPLOSS) != null && mItem.getString(GTSConst.JSON_KEY_STOPLOSS).length() > 0 && !mItem.getString(GTSConst.JSON_KEY_STOPLOSS).equals("0")) {
            m_spannableTitle.reset();
            m_spannableTitle.setForegroundColorSpanString(AppMain.getAppString(R.string.order_item_title_loss), ColorThemeUtil.instance().color_c);
            if (mItem.getInt(GTSConst.JSON_KEY_STOPLOSSSTATE) != 0) {
                m_spannableTitle.setBackgroundColorSpanString(
                        mItem.getString(GTSConst.JSON_KEY_STOPLOSS), ColorThemeUtil.instance().color_t);
            } else {
                m_spannableTitle.setBackgroundColorSpanString(
                        mItem.getString(GTSConst.JSON_KEY_STOPLOSS), ColorThemeUtil.instance().transparent);
            }
            mItemView.lossV.setText(m_spannableTitle.getBuilder());
            mItemView.lossV.setVisibility(View.VISIBLE);
        } else {
            mItemView.lossV.setText(AppMain.getAppString(R.string.order_item_title_loss) + 0);
            mItemView.lossV.setVisibility(View.VISIBLE);
        }
        if (mItem.getString(GTSConst.JSON_KEY_STOPPROFIT) != null && mItem.getString(GTSConst.JSON_KEY_STOPPROFIT).length() > 0 && !mItem.getString(GTSConst.JSON_KEY_STOPPROFIT).equals("0")) {
            m_spannableTitle.reset();
            m_spannableTitle.setForegroundColorSpanString(AppMain.getAppString(R.string.order_item_title_profit), ColorThemeUtil.instance().color_c);
            if (mItem.getInt(GTSConst.JSON_KEY_STOPPROFITSTATE) != 0) {
                m_spannableTitle.setBackgroundColorSpanString(
                        mItem.getString(GTSConst.JSON_KEY_STOPPROFIT), ColorThemeUtil.instance().color_t);
            } else {
                m_spannableTitle.setBackgroundColorSpanString(
                        mItem.getString(GTSConst.JSON_KEY_STOPPROFIT), ColorThemeUtil.instance().transparent);
            }
            mItemView.winV.setText(m_spannableTitle.getBuilder());
            mItemView.winV.setVisibility(View.VISIBLE);
        } else {
            mItemView.winV.setText(AppMain.getAppString(R.string.order_item_title_profit) + 0);
            mItemView.winV.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 判断颜色方向
     * @return
     */
    public void setClosePriceColor(TextView priceView, DataItemDetail mItem){
        if(mItem.getInt(GTSConst.JSON_KEY_DIRECTION) == AppContances.TRADE_TYPE_BUY){
            priceView.setText(mItem.getString(GTSConst.JSON_KEY_SELLPRICE));
            ColorThemeUtil.instance().setPriceColor(priceView,mItem.getInt(GTSConst.JSON_KEY_SELLPRICESTATE), mItem.getInt(GTSConst.JSON_KEY_SELLPRICEARRAW), true);
        }else{
            priceView.setText(mItem.getString(GTSConst.JSON_KEY_BUYPRICE));
            ColorThemeUtil.instance().setPriceColor(priceView,mItem.getInt(GTSConst.JSON_KEY_BUYPRICESTATE), mItem.getInt(GTSConst.JSON_KEY_BUYPRICEARRAW), true);
        }
    }

    @Override
    public int getLayoutID() {
        return R.layout.list_item_position;
    }

    @Override
    public RecyclerView.ViewHolder getViewHolder(View v, int type) {
        return new ListItemView(v);
    }

    public class ListItemView extends RecyclerView.ViewHolder{
        /** 产品名称 */
        @BindView(R.id.trade_prd_name)
        public TextView prdnameV;
        /** 买卖方向 */
        @BindView(R.id.trade_type)
        public TextView dirV;
        /** 开仓价 */
        @BindView(R.id.trade_open_price)
        public TextView donePrice;
        /** 平仓价 */
        @BindView(R.id.trade_close_price)
        public TextView closePrice;
        /** 时间 */
        @BindView(R.id.trade_time)
        public TextView timeV;
        /** 净盈亏 */
        @BindView(R.id.trade_profit)
        public TextView profitV;
        /** 止损 */
        @BindView(R.id.trade_open_loss)
        public TextView lossV;
        /** 止盈 */
        @BindView(R.id.trade_open_win)
        public TextView winV;
        /** 订单号 */
        @BindView(R.id.trade_order_id)
        public TextView orderIdV;
        /** 利息 */
        @BindView(R.id.trade_Swap)
        public TextView swapV;
        /** 手续费 */
        @BindView(R.id.trade_Commission)
        public TextView commissionV;
        @BindView(R.id.rl_content)
        public View content;
        /** 按钮布局 */
        @BindView(R.id.btn_layout)
        public View btnLayout;

        public ListItemView(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        @OnClick(R.id.content_layout)
        void onClickContent(){
            if(CommonUtils.isFastDoubleClick()){
                return;
            }
            final int positionKey = (int) itemView.getTag();
            DataItemDetail mItem = getItem(positionKey);
            Logger.i("content_layout按钮点击了");
            isClick = true;
            if (mExpandOrderId == mItem.getInt(GTSConst.JSON_KEY_ID)) {
                mExpandOrderId = -1;
            } else {
                mExpandOrderId = mItem.getInt(GTSConst.JSON_KEY_ID) ;
            }
            Logger.i("expandOrderId = " + mExpandOrderId);
            notifyDataSetChanged();
            if (null != mListV) {
                mListV.post(new Runnable() {
                    @Override
                    public void run() {
                        mListV.smoothScrollToPosition(positionKey);
                    }
                });
            }
        }

        @OnClick(R.id.close_btn)
        void onCloseOrder(){
            if(CommonUtils.isFastDoubleClick()){
                return;
            }
            final int positionKey = (int) itemView.getTag();
            DataItemDetail mItem = getItem(positionKey);
            Logger.i("close_btn按钮点击了");

            if(!checkTradable(mItem)){
                return;
            }

            ActivityManager.showCloseOrderActivity(mOwnerAct,mItem, AppContances.TRADE_TYPE_FORM_TRADE);
        }

        @OnClick(R.id.modify_btn)
        void onModityOrder(){
            if(CommonUtils.isFastDoubleClick()){
                return;
            }
            final int positionKey = (int) itemView.getTag();
            DataItemDetail mItem = getItem(positionKey);
            Logger.i("modify_btn按钮点击了");

            if(!checkTradable(mItem)){
                return;
            }

            ActivityManager.showOrderModifyActivity(mOwnerAct,mItem, AppContances.TRADE_TYPE_FORM_TRADE);
        }

        @OnClick(R.id.chart_btn)
        void onChartView(){
            if(CommonUtils.isFastDoubleClick()){
                return;
            }
            final int positionKey = (int) itemView.getTag();
            DataItemDetail mItem = getItem(positionKey);
            Logger.i("chart_btn按钮点击了");
            if (!NetworkMonitor.hasNetWork()) {
                return;
            }
            if(!ServerConnnectUtil.instance().isTradeConnect || !ServerConnnectUtil.instance().isQuoteConnect){
                ServerConnnectUtil.instance().reConnectServerConfirm(mOwnerAct);
                return;
            }
            if (null == mItem) {
                Logger.i("持仓数据对象为空！！！");
                showErrorMsg(ConfigType.SERVER_ERROR_1021);
                return;
            }
            if (mOwnerAct instanceof MainActivity) {
                RxBus.getInstance().post(NewQuoteFragment.CHANGE_QUOTE_EVENT, mItem.getInt(GTSConst.JSON_KEY_CODEID));
//                ((MainActivity) mOwnerAct).setTabFragment(ConfigType.TAB_QUOTE_TAG, "");//主界面，切换到行情

                //现在要改成，切换到这个产品的ChatActivity
                ActivityManager.showChartActivity(mOwnerAct, mItem.getInt(GTSConst.JSON_KEY_CODEID), mItem.getInt(GTSConst.JSON_KEY_ZONE), AppContances.TRADE_TYPE_FORM_QUOTE);
            }
        }
    }

    /**
     * 下单判断
     * @return
     */
    private boolean checkTradable(DataItemDetail mModel){

        if (!NetworkMonitor.hasNetWork()) {
            return false;
        }
        if (null == mModel) {
            Logger.i("持仓数据对象为空！！！");
            showErrorMsg(ConfigType.SERVER_ERROR_1021);
            return false;
        }

        if (!TradeBusiness.PreOrderCheck(mOwnerAct,  mModel.getInt(GTSConst.JSON_KEY_ZONE), mModel.getInt(GTSConst.JSON_KEY_TRADESTATE), false)) {
            return false;
        }

        return true;
    }

    private void showErrorMsg(String errorId){
        final PopupConfirmDialog dialog = PopupConfirmDialog.newInstance(mOwnerAct, "", ConfigUtil.instance().getErrorConfigObject().optString(errorId));
        dialog.show();
    }
}
